package com.house.controller;

import cn.hutool.core.bean.BeanUtil;
import com.house.dto.RoomDTO;
import com.house.entity.Room;
import com.house.service.RoomService;
import com.house.utils.Code;
import com.house.utils.Result;
import com.house.vo.RoomVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: GGP
 * @description: 房间控制层
 * @time: 2023-04-15 17:07
 **/
@Api("房间")
@RestController
@RequestMapping("/room")
@Validated
public class RoomController {

	@Resource
	private RoomService roomService;

	/**
	 * 条件筛选查询
	 * @param roomDTO
	 * @return
	 */
	@ApiOperation(value = "find",notes = "条件筛选查询")
	@PostMapping("/find")
	public Result findRoom(@RequestBody RoomDTO roomDTO){
		Map<String,Object> map=new HashMap<>(3);
		Page<Room> all = roomService.findAll(roomDTO);
		List<Room> content = all.getContent();
		List<RoomVO> roomsVO= BeanUtil.copyToList(content, RoomVO.class);
		map.put("rooms",roomsVO);
		map.put("totalPages",all.getTotalPages());
		map.put("totalElements",all.getTotalElements());
		return new Result(Code.GET_OK,map,"查询成功");
	}

	/**
	 * 添加房间
	 * @param roomDTO
	 * @return
	 */
	@ApiOperation(value = "save",notes = "添加房间")
	@PostMapping("/save")
	public Result saveRoom(@RequestBody @Valid RoomDTO roomDTO){
		RoomVO roomByNum = roomService.findRoomByNum(roomDTO);
		if (roomByNum!=null){
			return new Result(Code.SAVE_ERR,"添加失败，该房间已存在");
		}
		Room room = roomService.saveRoom(roomDTO);
		if (room==null){
			return new Result(Code.SYSTEM_ERR,"系统异常，请联系管理员！");
		}
		return new Result(Code.SAVE_OK,"添加成功");
	}

	/**
	 * 删除房间
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "delete",notes = "删除房间")
	@PostMapping(value = {"/delete/{id}"})
	public Result deleteRoom(@PathVariable Integer id){
		roomService.update(id,null);
		return new Result(Code.DELETE_OK,"删除成功");
	}
}
